﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using System.Reflection;

namespace SP.User.WebApi.Config
{
    public static class AtuofacConfig
    {
        public static void UseAutofac(this IHostBuilder host)
        {

            //对Auto进行一个配置
            host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            //配置IOC容器
            host.ConfigureContainer<ContainerBuilder>((c, b) =>
            {
                //单个注入
                // b.RegisterType<Service>()
                //.As<IService>()
                // .AsImplementedInterfaces()//注册为实现接口
                //.InstancePerDependency();//瞬态模式

                b.RegisterAssemblyTypes(Assembly.Load("SP.Service")).Where(s => s.Name.EndsWith("Service"))//类名以Service结尾的
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();

                //b.RegisterAssemblyOpenGenericTypes(Assembly.Load("SP.Domain"))
                //.AsImplementedInterfaces()
                //.InstancePerLifetimeScope();
                b.RegisterAssemblyTypes(Assembly.Load("SP.EFCore")).Where(s => s.Name.EndsWith("Repository"))//类名以Repository结尾的
                        .AsImplementedInterfaces()
                        .InstancePerLifetimeScope();

                b.RegisterAssemblyOpenGenericTypes(Assembly.Load("SP.EFCore"))
              .AsImplementedInterfaces()
              .InstancePerLifetimeScope();

            });
        }
    }
}
